<script lang="ts" setup>
import { ref, onMounted, watch, computed } from 'vue'
import setHeaderDialog from './dialogs/set-header-dialog.vue'
import gdgzDialog from './dialogs/gdgz-dialog.vue'
import gddjbDialog from './dialogs/gddjb-dialog.vue'
import pageExport from '@/components/page-export/index.vue'
import ExportUtil from '@/utils/table-export'
import { TitleItem } from '@/api/common'
import { getRygnpz } from '@/utils/table-header'
import { useMainStore } from '@/store/main'
import { useRoute } from 'vue-router'
import dayjs from 'dayjs'
const store = useMainStore()
const route = useRoute()
// 获取ref
const setHeaderRef = ref()

const emit = defineEmits([
  'selectionChange',
  'selectChange',
  'selectAllChange',
  'changeCurrent',
  'changeSize',
  'checkRow',
  'expandChange',
  'rowClick',
])

//暂无数据列表
const props = defineProps({
  gnbm: {
    type: String,
    default: '',
  },
  // 表格数据以及表头数据
  tableData: {
    type: Object,
    default: () => {
      return {}
    },
  },
  highlightCurrentRow: {
    type: Boolean,
    default: false,
  },
  // 设置斑马纹的颜色
  // stripeColor: {
  //   type: String,
  //   default: '#fff',
  // },
  // 表格高度
  tableHeight: {
    type: Number,
    default: 500,
  },
  // 表头样式
  headerCellStyle: {
    type: Object,
    default: () => {
      return { color: '#232932', background: '#ecf1fa' }
    },
  },
  // 表格样式
  cellStyle: {
    type: Object,
    default: () => {
      return { color: '#646a73', background: '#ffffff' }
    },
  },
  // 是否显示选择栏
  selectShow: {
    type: Boolean,
    default: true,
  },
  getTableDataParam: {
    type: Object,
  },
  // 是否展示折叠列
  expand: {
    type: Boolean,
    default: false,
  },
  // 是否是折叠子级表格
  expandChild: {
    type: Boolean,
    default: false,
  },
  // 是否展示表头
  showHeader: {
    type: Boolean,
    default: true,
  },
  height: {
    type: Number,
  },
  // key值
  rowKey: {
    type: String,
    default: '',
  },
  // 是否展示通用导出
  showExport: {
    type: Boolean,
    default: false,
  },
  // 导出参数
  formParams: {
    type: Object,
  },
  // 修改表头
  changeHeader: {
    type: Boolean,
    default: true,
  },
})

// 生命周期
onMounted(() => {
  if (props.gnbm) {
    // 获取表头
    getHeader()
  }
})

/*
 * 获取表头
 */
const tableHeader = ref<TitleItem[]>([])

const getHeader = async () => {
  const param = {
    dwbm: store.$state.userInfo.dwbm,
    rybm: store.$state.userInfo.ryid,
    gnbm: `${props.gnbm}-show`,
  }
  try {
    const value = (await getRygnpz(param)) as unknown as TitleItem[]
    tableHeader.value = value || props.tableData.titles
  } catch (error) {
    tableHeader.value = props.tableData.titles
  }
}
watch(
  () => props.tableData.titles,
  () => {
    // 获取表头
    getHeader()
  },
  { deep: true },
)
/*
 * 打开设置表头弹框
 */
const openHeaderDialog = () => {
  //
  setHeaderRef.value.openDialog()
}

// 选中项发生改变
const rowClick = (row: any, col: any, e: any) => {
  if (e.target?.tagName === 'IMG') return
  // if (multipleSelection.value?.includes(row)) {
  //   tableBoxRef.value?.handleEcho(row)
  // } else {
  //   tableBoxRef.value?.handleEcho(row)
  // }
  emit('rowClick', row)
}

// 选中项发生改变
const handleSelectionChange = (selection: any) => {
  emit('selectionChange', selection)
}

// 手动触发勾选
const handleSelectChange = (selection: any, row: any) => {
  emit('selectChange', selection, row)
}

// 手动触发全选
const handleSelectAllChange = (selection: any) => {
  emit('selectAllChange', selection)
}

const refTable = ref()
// 回显选中
const handleEcho = (echoData: any) => {
  clearSelection()
  if (echoData && echoData.length) {
    for (const row of echoData) {
      refTable.value.toggleRowSelection(row, true)
    }
  }
}
// 清空选择
const clearSelection = () => {
  refTable.value.clearSelection()
}

// 排序
const sortChange = (obj: any) => {
  console.log(obj, 'obj.prop')
}

/**
 * @描述: 分页相关
 */
// 选中页改变
const handleCurrentChange = (pageNum: number) => {
  emit('changeCurrent', pageNum)
}

// pageSize改变
const handleSizeChange = (pageSize: number) => {
  emit('changeSize', pageSize)
}

/**
 * 打开归档跟踪
 */
const gdgzDialogRef = ref<InstanceType<typeof gdgzDialog>>()
const openGdgzDialog = (gdbh: string) => {
  gdgzDialogRef.value!.openDialog(gdbh)
}

// 打开归档登记表
const gddjbDialogRef = ref<InstanceType<typeof gddjbDialog>>()
const openWsDialog = (arr: any) => {
  const gdbhList = arr.map((el: any) => el.gdbh)
  gddjbDialogRef.value!.openDialog(gdbhList, '归档登记表')
}

const checkRowClick = (row: any, e: Event, column: any) => {
  e.stopPropagation()
  emit('checkRow', row, column)
}

/**
 * 展开行
 */
const expandChange = (row: any, arr: any[]) => {
  emit('expandChange', row, arr)
}

/**
 * 导出
 */
const exportData = async (type: number) => {
  // 获取导出表头
  let exportHeader: TitleItem[] = []
  const param = {
    dwbm: store.$state.userInfo.dwbm,
    rybm: store.$state.userInfo.ryid,
    gnbm: `${props.gnbm}-export` || '',
  }
  const arr = ((await getRygnpz(param)) as unknown as TitleItem[]) || props.tableData.titles
  if (!arr.length) {
    exportHeader = props.tableData.titles
  } else {
    exportHeader = arr
  }
  // 表头
  const headerList = exportHeader.map((el: any) => {
    return {
      prop: el.prop,
      label: el.label,
    }
  })

  const params = {
    total: props.getTableDataParam?.total,
    http: {
      url: props.getTableDataParam?.exportParams.url,
      params: props.formParams,
    },
    excel: {
      wjmc: props.getTableDataParam?.exportParams.wjmc,
      headers: headerList,
    },
  }
  type === 1 ? ExportUtil.currentPage(params) : ExportUtil.allPage(params)
}

/**
 * 分页引入
 */
const getTableDataParam = computed(() => {
  const value = props.getTableDataParam || ({} as unknown as any)
  return value
})

defineExpose({ handleEcho, clearSelection, refTable, openGdgzDialog, openWsDialog })
</script>
<template>
  <div class="container">
    <el-table
      border
      ref="refTable"
      :data="props.tableData.data"
      :style="{ width: '100%', ...cellStyle }"
      :height="height ? height : '100%'"
      :header-cell-style="headerCellStyle"
      :cell-style="cellStyle"
      :min-height="tableHeight"
      :show-header="showHeader"
      :row-key="rowKey"
      :highlight-current-row="highlightCurrentRow"
      @selection-change="handleSelectionChange"
      @select="handleSelectChange"
      @select-all="handleSelectAllChange"
      @sort-change="sortChange"
      @expand-change="expandChange"
      @row-click="rowClick"
    >
      <el-table-column v-if="selectShow" type="selection" width="30" fixed="left" />
      <el-table-column v-if="changeHeader" width="35" fixed="left">
        <template #header>
          <div class="head-icon">
            <img
              @click="openHeaderDialog"
              src="@/assets/images/setting.png"
              alt=""
              class="pointer"
            />
          </div>
        </template>
        <template #default="scope">
          <div v-if="route.path === '/gdyj'">
            <el-tooltip
              v-if="scope.row.yjzt === '2'"
              :content="`该案件已办结，请及时进行归档流程，已${scope.row.syqx}!`"
              placement="top-start"
            >
              <img src="@/assets/images/warn-cq.png" alt="" />
            </el-tooltip>
            <el-tooltip
              v-else-if="scope.row.yjzt === '1'"
              :content="`该案件已办结，请及时进行归档流程，还有${scope.row.syqx}到期!`"
              placement="top-start"
            >
              <img src="@/assets/images/warning.png" alt="" />
            </el-tooltip>
          </div>

          <div
            style="
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
            "
            v-if="route.path === '/ajgd' || route.path === '/jzsm'"
          >
            <el-tooltip v-if="scope.row.yjjlList?.length" placement="top-start">
              <template #content>
                <div
                  v-for="el in scope.row.yjjlList.sort((a:any, b:any) => b.yjzt - a.yjzt)"
                  :key="el.gdbh"
                >
                  <div v-if="el.yjzt === '2'">
                    <span v-if="el.yjlx === '1'"
                      >该案件已归档，请及时进行归档流程，已超期【{{ el.yjqx }}】天</span
                    >

                    <span v-if="el.yjlx === '2'"
                      >该案件已退改，请及时进行归档流程，已超期【{{ el.yjqx }}】天</span
                    >
                    <span v-if="el.yjlx === '3'"
                      >该案件已审核退回，请及时进行归档流程，已超期【{{ el.yjqx }}】天</span
                    >
                    <span v-if="el.yjlx === '4'"
                      >该案件已借阅，请及时进行归档流程，已超期【{{ el.yjqx }}】天</span
                    >
                  </div>
                  <div v-if="el.yjzt === '1' && el.yjqx <= 5">
                    <span v-if="el.yjlx === '1'"
                      >该案件已归档，请重新提交归档审核，还剩【{{ el.yjqx }}】天到期</span
                    >
                    <span v-if="el.yjlx === '2'"
                      >该案件已退改，请重新提交归档审核，还剩【{{ el.yjqx }}】天到期</span
                    >
                    <span v-if="el.yjlx === '3'"
                      >该案件已审核退回，请重新提交归档审核，还剩【{{ el.yjqx }}】天到期</span
                    >
                    <span v-if="el.yjlx === '4'"
                      >该案件已借阅，请重新提交归档审核，还剩【{{ el.yjqx }}】天到期</span
                    >
                  </div>
                </div>
              </template>
              <img src="@/assets/images/warn-cq.png" alt="" />
            </el-tooltip>
            <el-tooltip v-else-if="scope.row.tgztdm === 'gd0150009'" placement="top-start">
              <template #content>
                <div v-if="scope.row.yjzt === '2'">
                  该案件已退改，请及时进行归档流程，已超期【{{
                    scope.row.yjqx || scope.row.tgsyts
                  }}】天
                </div>

                <div
                  v-else-if="
                    scope.row.yjzt === '1' && (scope.row.yjqx <= 5 || scope.row.tgsyts <= 5)
                  "
                >
                  该案件已退改，请重新提交归档审核，还剩【{{
                    scope.row.yjqx || scope.row.tgsyts
                  }}】天到期
                </div>
                <div v-else-if="!scope.row.yjzt && scope.row.tgsyts <= 5 && scope.row.yjqx <= 5">
                  该案件已退改，请重新提交归档审核，还剩【{{
                    scope.row.yjqx || scope.row.tgsyts
                  }}】天到期
                </div>
              </template>
              <img
                v-if="
                  scope.row.yjzt === '2' ||
                  scope.row.yjzt === '1' ||
                  (!scope.row.yjzt && scope.row.tgsyts <= 5 && scope.row.yjqx <= 5)
                "
                src="@/assets/images/warn-cq.png"
                alt=""
              />
            </el-tooltip>
            <el-tooltip
              v-if="scope.row.sfsd === 'Y'"
              :content="`${scope.row.sdmsxx}`"
              placement="top-start"
            >
              <img style="margin-left: -3px" src="@/assets/images/24gf-lock2.png" alt="" />
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <!--是否展示折叠行-->
      <el-table-column type="expand" v-if="expand" width="30">
        <template #default="props">
          <slot name="expand" :props="props"></slot>
        </template>
      </el-table-column>
      <!--占位列-->
      <el-table-column v-else-if="expandChild" width="85" />
      <el-table-column
        v-for="item in tableHeader"
        resizable
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        show-overflow-tooltip
        :align="item.dqfs || 'left'"
        :sortable="true"
      >
        <template #default="scope">
          <div v-if="item.custom">
            <el-link
              type="primary"
              class="custom-link"
              :underline="false"
              @click="checkRowClick(scope.row, $event, item)"
              >{{ item.fjxx ? '附件' : scope.row[item.prop] }}
              <span class="fjsl" v-if="item.fjxx"> {{ scope.row[item.prop] }} </span>
            </el-link>
          </div>
          <div v-if="item.clyjyjb">
            <el-link
              v-if="scope.row.clyjwjbh"
              type="primary"
              class="custom-link"
              :underline="false"
              @click="checkRowClick(scope.row, $event, item)"
              >{{ scope.row[item.prop] }}
            </el-link>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </div>
          <div v-if="item.yjfkyjb">
            <el-link
              v-if="scope.row.yjfkwjbh"
              type="primary"
              class="custom-link"
              :underline="false"
              @click="checkRowClick(scope.row, $event, item)"
              >{{ scope.row[item.prop] }}
            </el-link>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </div>
          <div v-else-if="item.format">
            <span>{{
              typeof item.format === 'string'
                ? scope.row[item.prop]
                  ? dayjs(scope.row[item.prop]).format(item.format)
                  : ''
                : item.format[scope.row[item.prop]]
            }}</span>
          </div>
          <div v-else-if="item.jczt">
            <span class="jczt" v-if="scope.row[item.prop] === '未检测'">
              <img src="@/assets/images/nottest.png" alt="" />
              <span style="color: #526a89">{{ scope.row[item.prop] }}</span>
            </span>
            <span class="jczt" v-else-if="scope.row[item.prop] === '检测中'">
              <img src="@/assets/images/testing.png" alt="" />
              <span style="color: #00a5ef">{{ scope.row[item.prop] }}</span>
            </span>
            <span class="jczt" v-else-if="scope.row[item.prop] === '检测通过'">
              <img src="@/assets/images/success.png" alt="" />
              <span style="color: #09ad43">{{ scope.row[item.prop] }}</span>
            </span>
            <span class="jczt" v-else-if="scope.row[item.prop] === '检测不通过'">
              <img src="@/assets/images/fail.png" alt="" />
              <span style="color: #ff5050">{{ scope.row[item.prop] }}</span>
            </span>
          </div>
          <div v-else-if="item.shzt">
            <el-tooltip placement="right" effect="light">
              <template #content>
                <div style="color: #000; font-weight: 700">当前: {{ scope.row[item.prop] }}</div>
                <div style="color: #a09bb8" v-if="props.gnbm === 'ajgd-ytj'">
                  {{
                    ['gd0180004', 'gd0180003'].includes(scope.row.gdjddm) ? '审核角色' : '审核人'
                  }}:
                  {{
                    ['gd0180004', 'gd0180003'].includes(scope.row.gdjddm)
                      ? scope.row.gdshjsmc || scope.row.gdshrxm
                      : scope.row.gdshrxm
                  }}
                </div>
                <div style="color: #a09bb8" v-if="props.gnbm === 'ajgd-yth'">
                  退回原因: {{ scope.row.thyy }}
                </div>
                <div style="color: #000; font-weight: 700" v-if="props.gnbm === 'ajgd-yth'">
                  退回期限: {{ scope.row.syqx }}
                </div>
                <div style="color: #000; font-weight: 700" v-if="props.gnbm === 'ajgd-tgz'">
                  <div v-if="scope.row.yjzt === '2'">退改期限: 超期{{ scope.row.tgqx }} 天</div>
                  <div v-if="scope.row.yjzt === '1'">退改期限: 预警{{ scope.row.tgqx }} 天</div>
                  <div v-if="!scope.row.yjzt && !scope.row.yjqx">
                    退改期限: 剩余{{ scope.row.tgqx }} 天
                  </div>
                </div>

                <div style="color: #a09bb8" v-if="props.gnbm === 'ajgd-tgjl'">
                  审批人: {{ scope.row.jdcljsmc || scope.row.dayshrxm || scope.row.jdclrxm }}
                </div>
                <!-- <div
                  style="color: #000; font-weight: 700"
                  v-if="props.gnbm === 'ajgd-tgjl' && scope.row[item.prop] === '退改中'"
                >
                  退改期限: {{ scope.row.tgqx }}
                </div> -->
                <div style="color: #a09bb8" v-if="props.gnbm === 'jyd'">
                  审批人: {{ scope.row.dqshrmc || scope.row.dqshjsmc }}
                </div>
              </template>
              <span>{{ scope.row[item.prop] }}</span>
            </el-tooltip>
          </div>
          <div v-else-if="item.gdzt">
            <span v-if="scope.row[item.prop] === '未归档'">
              <span style="color: #ff8800">{{ scope.row[item.prop] }}</span>
            </span>
            <span v-else-if="scope.row[item.prop] === '超期未归档'">
              <span style="color: #ff4747">{{ scope.row[item.prop] }}</span>
            </span>
            <span v-else-if="scope.row[item.prop] === '按期归档'">
              <span style="color: #09ad43">{{ scope.row[item.prop] }}</span>
            </span>
            <span v-else-if="scope.row[item.prop] === '超期归档'">
              <span style="color: #ff4747">{{ scope.row[item.prop] }}</span>
            </span>
          </div>

          <span v-else-if="item.specialdalx">
            {{
              scope.row[item.prop]
                ? scope.row[item.prop].map((lx: any) => lx.jydalxmc).join(',')
                : undefined
            }}
          </span>
        </template>
      </el-table-column>
      <slot name="myAction"></slot>
      <template #empty>
        <div class="empty" :style="{ height: tableHeight - 44 + 'px', ...cellStyle }">暂无数据</div>
      </template>
    </el-table>
    <!--分页-->
    <page-export
      v-model="getTableDataParam"
      :showExport="showExport"
      @changeSize="handleSizeChange"
      @changeNum="handleCurrentChange"
      @exportAll="exportData(2)"
      @exportCurrentPage="exportData(1)"
    />
    <setHeaderDialog
      ref="setHeaderRef"
      :gnbm="props.gnbm"
      :showExport="showExport"
      :tableHeade="props.tableData.titles"
      @refresh="getHeader"
    ></setHeaderDialog>
    <!--归档跟踪-->
    <gdgz-dialog ref="gdgzDialogRef" />
    <!--归档登记表-->
    <gddjb-dialog ref="gddjbDialogRef" />
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: calc(100% - 2px) !important;
  :deep(.custom-link) {
    width: 100%;
    display: block;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    .el-link__inner {
      display: inline;
    }
    .fjsl {
      display: inline-block;
      width: 18px;
      height: 18px;
      line-height: 18px;
      border-radius: 50%;
      text-align: center;
      background-color: #f86359;
      color: #fff;
    }
  }
  .el-table--border::after {
    width: 0;
  }
  :deep(.el-table__cell) {
    border-right: 0 !important;
  }
  :deep(.el-table__border-left-patch) {
    display: none;
  }
}

.a-hover:hover {
  text-decoration: underline;
}

.head-icon {
  display: flex;
  align-items: center;
  img {
    width: 18px;
    height: 18px;
    // margin-right: ;
  }
}

.el-pagination {
  justify-content: flex-end;
}

.pointer {
  cursor: pointer;
}
// 解决表格滚动条错乱
.el-table__body-wrapper {
  .el-scrollbar .el-scrollbar__view {
    height: auto;
  }
  .el-table__empty-text {
    // height: 100%;
    // display: flex;
    // align-items: center;
    // justify-content: center;
    .empty {
      height: 100% !important;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.jczt {
  display: flex;
  align-items: center;
  img {
    margin-right: 4px;
  }
}
</style>
